package com.atguigu.gulimall.member.service.impl;

import com.atguigu.common.utils.HttpClientUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistExecetion;
import com.atguigu.gulimall.member.exception.UsernameExistExecetion;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Autowired
    MemberDao memberDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
//        MemberLevelDao memberLevelDao = new BaseMapper<MemberEntity>();
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        //用户名、手机号应该是唯一的，这里再进行保存以前要进行唯一性校验

        //为了让controller感知异常，进行异常机制处理
//        if(checkPhoneUnique(vo.getPhone())){
//
//        }

        checkUsernameUnique(vo.getUserName());
        checkPhoneUnique(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());

        //密码进行加密处理
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String md5Password = encoder.encode(vo.getPassword());
        memberEntity.setPassword(md5Password);

        memberEntity.setNickname(vo.getUserName());

        MemberDao memberDao = this.baseMapper;
        memberDao.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistExecetion{
        Integer mobileCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile",phone));
        if(mobileCount>0){
            throw new PhoneExistExecetion();
        }
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameExistExecetion{
        Integer userCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username",userName));
        if(userCount>0){
            throw new UsernameExistExecetion();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //1、去数据库查询
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username",loginacct)
                .or().eq("mobile",loginacct));
        if(memberEntity==null){
            //登陆失败
            return null;
        }else{
            //获取数据库的password
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matched = encoder.matches(password,memberEntity.getPassword());
            if(matched){
                //匹配成功，登陆成功
                return memberEntity;
            }else{
                //匹配失败返回空
                return null;
            }
        }
    }

    /**
     * 社交账号，具有注册和登陆合并逻辑
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(SocialUserVo vo) {
        String uid = vo.getUid();
        //1、判断当前社交用户是否已经登陆过系统（是否注册过）
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid",uid));
        if(memberEntity!=null){
            //已经登陆过了，说明注册过当前UID
            MemberEntity updateEntity = new MemberEntity();
            updateEntity.setId(memberEntity.getId());
            updateEntity.setSocialToken(vo.getAccess_token());
            updateEntity.setExpiresIn(vo.getExpires_in());

            memberDao.updateById(updateEntity);
            memberEntity.setSocialToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            return memberEntity;
        }else{
            //没有查到当前社交用户，就需要进行注册
            MemberEntity inserEneity = new MemberEntity();
            //todo 查处当前用户的昵称，性别，等信息
            Map<String,String> map = new HashMap<>();
            map.put("access_token",vo.getAccess_token());
            map.put("uid",vo.getUid());
            String result = HttpClientUtils.ajaxPost("api.weibo.com/2/users/show.json",map);
        }
        return null;
    }

}